package com.itcs.box.server.server;

import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.itcs.box.server.service.NettyMsgResolveService;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * 
 * @author LiuPeng
 * 
 */
public class NettyServerBootstrap {

	private Log logger = LogFactory.getLog(NettyChannelMap.class);

	private NettyMsgResolveService nettyMsgResolveService;
	private int port;

	public NettyServerBootstrap(int port, NettyMsgResolveService nettyMsgResolveService) {
		this.nettyMsgResolveService = nettyMsgResolveService;
		this.port = port;
		bind();
	}

	private void bind() {
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(boss, worker);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.option(ChannelOption.SO_BACKLOG, 128);
			bootstrap.option(ChannelOption.TCP_NODELAY, true);
			bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
			bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel socketChannel) throws Exception {
					ChannelPipeline p = socketChannel.pipeline();
					// p.addLast(new ObjectEncoder());
					// p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
					p.addLast(new IdleStateHandler(60*5, 0, 0, TimeUnit.SECONDS));
					p.addLast(new JsonObjectDecoder(1024*10));
					p.addLast(new NettyServerHandler(nettyMsgResolveService));
				}
			});
			ChannelFuture f = bootstrap.bind(port).sync();
			if (f.isSuccess()) {
				logger.info("netty server start ...");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
